import axios from 'axios';
import {
  Message
} from 'element-ui';
import store from '../store';
import {
  getToken
} from '@/utils/auth';

const language = store.state.app.language || 'zh';
const lanMap = {
  zh: 'zh-Hans',
  en: 'en-US',
  km: 'km-KH'
};
const lan = lanMap[language];

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 100000
});

// request拦截器
service.interceptors.request.use(
  config => {
    // 本地开发自动加上token
    if (store.getters.token || process.env.NODE_ENV == 'development') {
      config.headers['X-Token'] = getToken(); // 数据后台
      config.headers['x-auth-token'] = getToken(); // 生活管理后台
    }
    config.headers['lan'] = lan;
    return config;
  },
  error => {
    Promise.reject(error);
  }
);
// response 拦截器
service.interceptors.response.use(
  response => {
    /**
           * code为非200是抛错 ,兼容ip查询接口state
           */
    const res = response.data;
    if (response.config.resolveWithFullResponse) {
      return response;
    }
    if (res.code !== 200 && res.state != 1) {
      Message({
        message: res.msg || res.clientMsg || res.error_msg,
        type: 'error',
        duration: 5 * 1000
      });
      /**
             * 999: Token过期了;
             */
      if (res.code === 999) {
        store.dispatch('FedLogOut').then(() => {
          location.reload(); // 为了重新实例化vue-router对象 避免bug
        });
      }
      return Promise.reject('error');
    } else {
      return response.data;
    }
  },
  error => {
    Message({
      message: '网络错误',
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
